package rule

import (
	"time"
	"encoding/json"
	"errors"
	"go-iot/app/iot/core"
	"go-iot/app/iot/eventbus"
	"go-iot/app/iot/eventbus/message"
	"go-iot/app/models"
	//"go-iot/app/iot/ruleengine"
	"go-iot/app/common/mysql"
	"go-iot/app/common/logger"
)

func init() {
	eventbus.Subscribe(eventbus.GetAlarmTopic("*", "*"), saveAlarmEvent)
}

func saveAlarmEvent(data message.Message) {
	if data == nil {
		return
	}
	if t, ok := data.(*message.AlarmMessage); ok {
		b, err := json.Marshal(t.Data)
		if err != nil {
			logger.Errorf(err.Error())
			return
		}
		device := core.GetDevice(t.DeviceId)
		if device == nil {
			logger.Errorf("saveAlarmEvent error: device not found")
			return
		}
		log := models.AlarmLog{
			ProductId: t.ProductId,
			DeviceId:  t.DeviceId,
			RuleId:    t.RuleId,
			CreateId:  device.GetCreateId(),
			AlarmName: t.AlarmName,
			AlarmData: string(b),
			CreateTime: time.Now(),
			State:     "unsolve",
		}

		if err := mysql.DB.Create(&log).Error; err != nil {
			logger.Errorf("保存告警日志失败: %s", err.Error())
		}
	}
}

func PageAlarmLog(page *models.PageQuery, createId int64) (*models.PageResult[models.AlarmLog], error) {
	var alarmLogs []models.AlarmLog
	var count int64
	
	// 构建查询条件
	query := mysql.DB.Model(&models.AlarmLog{})
	
	// 添加过滤条件
	if len(page.Condition) > 0 {
		for _, term := range page.Condition {
			query = query.Where(term.Key+" = ?", term.Value)
		}
	}
	
	// 添加创建者ID过滤
	query = query.Where("create_id = ?", createId)
	
	// 如果有SearchAfter，添加相应条件
	if len(page.SearchAfter) > 0 && len(page.SearchAfter) >= 2 {
		query = query.Where("(create_time < ? OR (create_time = ? AND id < ?))", 
			page.SearchAfter[0], page.SearchAfter[0], page.SearchAfter[1])
	}
	
	// 计算总数
	err := query.Count(&count).Error
	if err != nil {
		return nil, err
	}
	
	// 查询数据
	err = query.Order("create_time DESC, id DESC").
		Limit(page.PageSize).
		Offset(page.PageOffset()).
		Find(&alarmLogs).Error
	if err != nil {
		return nil, err
	}
	
	// 获取最后一条记录的SearchAfter值
	var lastSort []interface{}
	if len(alarmLogs) > 0 {
		lastAlarm := alarmLogs[len(alarmLogs)-1]
		lastSort = []interface{}{lastAlarm.CreateTime, lastAlarm.Id}
	}
	
	// 构建分页结果
	result := models.PageUtil(count, page.PageNum, page.PageSize, alarmLogs)
	result.SearchAfter = lastSort
	
	return &result, nil
}

func SolveAlarmLog(q models.AlarmLog) error {
	if q.Id == 0 {
		return errors.New("id must be present")
	}
	
	// 设置状态为已解决
	q.State = "solve"
	
	// 使用GORM更新数据
	return mysql.DB.Model(&q).Updates(map[string]interface{}{
		"state": q.State,
		"desc": q.Desc,
	}).Error
}
